package com.zxhysy.log.annotation.context;

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

/**
 * 日志内容补充，用于el表达式，采用  stack 目的是递归时做到方法间的参数隔离
 * @author zhangxinhong
 * @since 2022/1/24 15:58
 */
public class LogContext {
    /**
     * logContext 上下文信息载体
     */
    private static final InheritableThreadLocal<Stack<Map<String, Object>>> VARIABLE_STACK_MAP = new InheritableThreadLocal<>();

    public static Map<String, Object> getVariables() {
        return VARIABLE_STACK_MAP.get().lastElement();
    }

    /**
     * 设置空元素
     */
    public static void putEmpty() {
        Stack<Map<String, Object>> stack = VARIABLE_STACK_MAP.get();
        if (stack == null) {
            stack = new Stack<>();
            VARIABLE_STACK_MAP.set(stack);
        }
        stack.add(new HashMap<>(16));
    }

    /**
     * 设置上下文属性
     * @param key   key
     * @param value value
     */
    public static void putVariable(String key, Object value) {
        VARIABLE_STACK_MAP.get().lastElement().put(key, value);
    }

    /**
     * 清楚元素
     */
    public static void clean() {
        VARIABLE_STACK_MAP.get().pop();
        if (VARIABLE_STACK_MAP.get().isEmpty()) {
            VARIABLE_STACK_MAP.remove();
        }
    }

}
